import logging

from absl import flags
from sqlalchemy import create_engine
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import sessionmaker

from coin.base.database.database import DatabaseConnectorBase

flags.DEFINE_string('db_config',
                    "coin/support/exchange_status/config/db_config_prod.json",
                    'path of database config.')


def _gen_sqlalchemy_connection(engine):
  session_maker = sessionmaker(bind=engine, autoflush=False)
  connection = session_maker()
  return connection


def _gen_sqlalchemy_engine(db_config):
  host = db_config.get('host', '')
  db = db_config.get('database', '')
  user = db_config.get('user', '')
  passwd = db_config.get('password', '')
  engine_name = 'mysql+mysqldb://%s:%s@%s/%s' % (user, passwd, host, db)
  engine = create_engine(engine_name)
  return engine


def gen_sqlalchemy_query_engine():
  engine = create_engine(
      'mysql+mysqldb://status_querier:qzeV%ExVrr$@zaw@@coin-db.cc4jwamep7jm.ap-northeast-2.rds.amazonaws.com/coin_exchange_status_20180410',
      echo=False)
  return engine


class ExchangeStatusConnector(DatabaseConnectorBase):
  def __init__(self, connection=None, close_connection_on_exit=True, logger=None):
    super().__init__(connection=connection,
                     close_connection_on_exit=close_connection_on_exit,
                     logger=logging.getLogger(__name__))

    self._engine = self._connection.get_bind()
    self._automap_base = automap_base()
    self._automap_base.prepare(self._engine, reflect=True)
    self._RestStatus = self._automap_base.classes.RestStatusHistory
    self._FeedStatus = self._automap_base.classes.FeedStatusHistory
    self._OrderStatus = self._automap_base.classes.OrderStatusHistory
    self._ExchangeStatus = self._automap_base.classes.ExchangeStatusHistory

  @classmethod
  def create_connector(cls, db_config=None, connection=None):
    assert (db_config is not None) ^ (connection is not None)
    if connection is None:
      engine = _gen_sqlalchemy_engine(db_config)
      connection = _gen_sqlalchemy_connection(engine)
    return cls(connection=connection)
